<template>
  <div class="body1">
    <div class="no-print el-button-print">
      <el-button @click="exportPDF">导出为pdf</el-button>
    </div>
    <div class="body2" id="pdfDom" :class="{ 'pdf-export': isPdfExport }">
      <div class="title">
        <div class="biaotididian">{{ agencyName }}</div>
        <div class="biaoti">轻微违法违规行为免罚告知承诺书</div>
      </div>
      <div class="foreword">
        <input v-model="form.d1" :resize="'none'" autosize maxlength="4" class="inputStyle1"
          style="width: 80px;font-family: 仿宋;font-size: 5mm;text-align: center" type="textarea">
        <span>（</span>
        <reference-select style="width: 5mm;margin-bottom: 4px" v-model="form.referenceValue"
          class="InvestigatorSelectReplace" />
        <span>）NO：</span>
        <input v-model="form.d2" :resize="'none'" autosize maxlength="6" class="inputStyle"
          style="width: 120px;font-family: 仿宋;font-size: 5mm;text-align: center" type="textarea" ref="inputRef6">
      </div>
      <table class="tableStyle">
        <colgroup>
          <col width="7%">
          <col width="18%">
          <col width="34%">
          <col width="19%">
          <col width="22%">
        </colgroup>
        <tbody>
          <tr>
            <td rowspan="3" style="text-align: center;">
              当事<br>
              人情<br>
              况
            </td>
          </tr>

          <tr>
            <td style="height: 50px; text-align: center;">姓名/名称</td>
            <td style="">
              <privy-info-select-return-array v-model="form.unitName" :isTable="true" maxLength="22" return-fields="A"
                :return-array-template="[
                  { name: 'companyLicense', field: 'B' },
                  { name: 'companyAddress', field: 'E' },
                  { name: 'legalPersonPhone', field: 'H' },
                ]" @select="selectUnitUpdateData">
              </privy-info-select-return-array>
            </td>

            <td style="text-align: center">
              <span>身份证件号/信用代码</span>
            </td>
            <td>
              <el-input v-model="form.companyLicense" maxlength="28" :resize="'none'" autosize class="areaInputStyle"
                type="textarea" oninput="this.value = this.value.replace(/[^a-zA-Z0-9_-]/g, '')" />
            </td>
          </tr>
          <tr>
            <td style="height: 50px; text-align: center;">地址</td>
            <td>
              <el-input v-model="form.companyAddress" maxlength="22" :resize="'none'" autosize class="areaInputStyle"
                type="textarea" />
            </td>

            <td style="text-align: center">
              <span>联系电话</span>
            </td>
            <td>
              <el-input v-model="form.legalPersonPhone" maxlength="28" :resize="'none'" autosize class="areaInputStyle"
                type="textarea" oninput="this.value = this.value.replace(/[^a-zA-Z0-9_-]/g, '')" />
            </td>
          </tr>
          <tr>
            <td style="height: 330px; text-align: center;">
              <span>违法</span><br>
              <span>行为</span><br>
              <span>告知</span>
            </td>
            <td colspan="4" style="text-align: left;vertical-align: top; position: relative;">
              <div>
                &nbsp;&nbsp;&nbsp;&nbsp;<editable-textarea :text="form.date1" param-type="YYYYMMDD1"
                  @send-to-parent="receiveFromChild"></editable-textarea>
                <span>，执法人员</span>
                <input v-model="form.a6" :resize="'none'" autosize maxlength="6" class="inputStyle"
                  style="width: 130px;font-family: 仿宋;font-size: 5mm;" type="textarea">
                <span>、</span>
                <input v-model="form.a7" :resize="'none'" autosize maxlength="6" class="inputStyle"
                  style="width: 130px;font-family: 仿宋;font-size: 5mm;" type="textarea">
                <span>，在</span>
                <input v-model="form.a8" :resize="'none'" autosize maxlength="18" class="inputStyle"
                  style="width: 350px;font-family: 仿宋;font-size: 5mm;" type="textarea">
                <span>，发现当事人存在</span>
                <LawsAndRegulationsSelect v-model:illegalActText="form.a9" v-model:returnIllegalTermsString="form.a10"
                  v-model:returnIllegalBasisString="form.a11" width="100px" />
                <span>违法行为，违反了</span>
                <span v-if="form.a10" class="span-underline">{{ form.a10 }}</span><span v-else
                  class="span-underline">&nbsp;&nbsp;</span>
                <sapn>的规定，根据</sapn>
                <span v-if="form.a11" class="span-underline">{{ form.a11 }}</span>
                <span v-else class="span-underline">&nbsp;&nbsp;</span>
                <span>的规定，现责令当事人（</span>
                <input type="checkbox" v-model="form.checkbox1"><span>立即/</span>
                <input type="checkbox" v-model="form.checkbox2"><span>于</span>
                <editable-textarea :text="form.date2" param-type="YYYYMMDD2"
                  @send-to-parent="receiveFromChild"></editable-textarea>
                <span>前）按下列要求改正违法行为：</span>
                <input v-model="form.a12" :resize="'none'" autosize maxlength="26" class="inputStyle"
                  style="width: 500px;font-family: 仿宋;font-size: 5mm;" type="textarea">。
                <br>
                <span>&nbsp;&nbsp;&nbsp;&nbsp;经查，（</span>
                <input type="checkbox" v-model="form.checkbox3">
                <span>当事人的违法行为轻微，没有造成危害后果/</span>
                <input type="checkbox" v-model="form.checkbox4">
                <span>当事人属于初次违法，危害后果轻微），符合轻微违法违规行为免予行政处罚的使用条件。执法人员已向当事人宣传了相关法律法规规章的规定。</span>
              </div>

              <div
                style="position: absolute; bottom: 10px; left: 20px; right: 20px; display: flex; justify-content: space-between; align-items: flex-end; margin-top: 20px;">
                <div style="display: flex; align-items: flex-end;">
                  执法人员签名：
                  <SignatureField label="签名1" sign-type="sign1" :img-url="form.img1"
                    @update:imgUrl="form.img1 = $event" />，
                  <SignatureField label="签名2" sign-type="sign2" :img-url="form.img2"
                    @update:imgUrl="form.img2 = $event" />
                </div>
                <div>
                  <editable-textarea :text="form.date3" param-type="YYYYMMDD3"
                    @send-to-parent="receiveFromChild"></editable-textarea>
                </div>
              </div>
            </td>
          </tr>
          <tr style="height: 270px;">
            <td style="text-align: center;">
              当事<br>
              人承<br>
              诺
            </td>
            <td colspan="4" style="text-align: left;vertical-align: top; position: relative;">
              <div>
                {{ form.commitAgencyName }}：<br>
                &nbsp;&nbsp;&nbsp;&nbsp;执法人员<input v-model="form.a13" :resize="'none'" autosize maxlength="6"
                  class="inputStyle" style="width: 130px;font-family: 仿宋;font-size: 5mm;" type="textarea">、<input
                  v-model="form.a14" :resize="'none'" autosize maxlength="6" class="inputStyle"
                  style="width: 130px;font-family: 仿宋;font-size: 5mm;" type="textarea">已向本人（单位）进行了相关告知和法治宣传教育，并要求予以改正。
                <br>
                &nbsp;&nbsp;&nbsp;&nbsp;本人（单位）对以上情况确认无误，并自愿承诺：<br>
                &nbsp;&nbsp;&nbsp;&nbsp;<input type="checkbox" v-model="form.checkbox5">1.立即予以改正；<br>
                &nbsp;&nbsp;&nbsp;&nbsp;<input type="checkbox"
                  v-model="form.checkbox6">2.在年月日前修正完毕，并将整改情况说明等材料送达你单位；<br>
                &nbsp;&nbsp;&nbsp;&nbsp;<input type="checkbox" v-model="form.checkbox7">3.遵守相关城市管理法律法规规章的规定。<br>
                &nbsp;&nbsp;&nbsp;&nbsp;若本人（单位）未履行上述承诺的或再有相同违法行为发生的，愿依法承担相应的法律责任。
                <div
                  style="position: absolute; bottom: 10px; left: 20px; right: 20px; display: flex; justify-content: space-between; align-items: flex-end; margin-top: 20px;">
                  <div style="display: flex; align-items: flex-end;">
                    签名或盖章：
                    <SignatureField label="签名3" sign-type="sign3" :img-url="form.img3"
                      @update:imgUrl="form.img3 = $event" />
                  </div>
                  <div>
                    <editable-textarea :text="form.date4" param-type="YYYYMMDD4"
                      @send-to-parent="receiveFromChild"></editable-textarea>
                  </div>
                </div>
              </div>
            </td>
          </tr>
          <tr style="height: 70px;">
            <td style="text-align: center;">
              备注<br>
              情况
            </td>
            <td colspan="4" style="text-align: left;vertical-align: top; position: relative;">
              <div class="input-bottom-div">
                &nbsp;&nbsp;&nbsp;&nbsp;改正复查情况:<input v-model="form.a15" :resize="'none'" autosize maxlength="20"
                  class="inputStyle" style="width: 380px;font-family: 仿宋;font-size: 5mm;" type="textarea">
                <div
                  style="position: absolute; bottom: 10px; left: 20px; right: 20px; display: flex; justify-content: space-between; align-items: flex-end; margin-top: 20px;">
                  <div style="display: flex; align-items: flex-end;">
                    执法人员签名：
                    <SignatureField label="签名4" sign-type="sign4" :img-url="form.img4"
                      @update:imgUrl="form.img4 = $event" />，
                    <SignatureField label="签名5" sign-type="sign5" :img-url="form.img5"
                      @update:imgUrl="form.img5 = $event" />
                  </div>
                  <div>
                    <editable-textarea :text="form.date5" param-type="YYYYMMDD5"
                      @send-to-parent="receiveFromChild"></editable-textarea>
                  </div>
                </div>
              </div>
            </td>
          </tr>
        </tbody>
      </table>
      <!-- <p style="font-family: '仿宋', serif; font-size: 5mm;">附：当事人的身份材料复印件及其他证明材料</p> -->
    </div>
  </div>
</template>

<script>
import EditableTextarea from "@/views/template/EditableTextarea";
import { agencyName, sealName, commitAgencyName } from "../../utils/publicName.js"
import PrivyInfoSelectReturnArray from "@/views/template/PrivyInfoSelectReturnArray";
import SignatureField from "@/views/template/SignatureField";
import LawsAndRegulationsSelect from "@/views/template/LawsAndRegulationsSelect";
import ReferenceSelect from "@/views/template/ReferenceSelect";

export default {
  components: {
    EditableTextarea,
    SignatureField,
    LawsAndRegulationsSelect,
    ReferenceSelect,
    PrivyInfoSelectReturnArray,
  },

  data() {
    return {
      agencyName: agencyName,
      sealName: sealName,
      form: {
        commitAgencyName: commitAgencyName,
      },
      isPdfExport: false, // 控制打印样式
    }
  },
  created() {
    window.parent.getTemplateData((data) => {
      this.form = data;
    })
    window.postForm = () => {
      this.postForm();
    }
  },

  mounted() {
    window.parent.changeTemplateDow();
  },

  methods: {

    // 导出为pdf
    exportPDF() {
      this.savePDF()
        .then((blob) => {
          const blobUrl = URL.createObjectURL(blob);

          // 先预览
          const previewWindow = window.open(blobUrl, '_blank');

          // 自动下载
          const fileName = `轻微违法违规行为免罚告知承诺书.pdf`;
          const downloadLink = document.createElement('a');
          downloadLink.href = blobUrl;
          downloadLink.download = fileName;
          document.body.appendChild(downloadLink);
          downloadLink.click();
          document.body.removeChild(downloadLink);

          // 监听预览窗口关闭后释放内存
          if (previewWindow) {
            const timer = setInterval(() => {
              if (previewWindow.closed) {
                clearInterval(timer);
                URL.revokeObjectURL(blobUrl);
              }
            }, 1000);
          } else {
            setTimeout(() => URL.revokeObjectURL(blobUrl), 10000); // 兜底释放
          }
        })
        .catch(error => {
          console.error('导出PDF出错:', error);
          alert('导出失败，请重试或联系管理员');
        });
    },
    savePDF() {
      this.isPdfExport = true; // 激活PDF样式
      return new Promise((resolve, reject) => {
        this.$nextTick(() => {
          import('html2pdf.js').then((module) => {
            const html2pdf = module.default;

            //获取所有需要替换的 el-input
            const elInputs = document.querySelectorAll('.el-input__inner, .el-textarea__inner');

            //存储原始元素和它们的父节点，方便后续恢复
            const originalElements = [];

            elInputs.forEach((input) => {
              const div = document.createElement('div');
              div.style.whiteSpace = 'pre-wrap'; // 保留换行
              div.style.fontFamily = '仿宋';
              div.style.fontSize = '5mm';
              div.textContent = input.value; // 保留原内容（自动处理 \n 换行）
              div.style.lineHeight = '1.3';

              // 替换 el-input，并存储原始元素
              originalElements.push({
                parent: input.parentNode,
                original: input,
                replacement: div,
              });
              input.parentNode.replaceChild(div, input);
            });

            // 配置选项
            const opt = {
              margin: 0,
              image: {
                type: 'jpeg',
                quality: 0.98
              },
              html2canvas: {
                scale: 2,
                logging: false,
                useCORS: true
              },
              jsPDF: {
                unit: 'mm',
                format: 'a4',
                orientation: 'portrait'
              }
            };

            const element = document.getElementById('pdfDom');

            // 生成PDF Blob对象
            html2pdf()
              .set(opt)
              .from(element)
              .toPdf()
              .get('pdf')
              .then((pdf) => {
                const blob = pdf.output('blob');

                resolve(blob); // 返回Blob对象
              })
              .catch((error) => {
                reject(error);
              })
              .finally(() => {
                this.isPdfExport = false; // 恢复原始样式
                // 恢复原始input
                originalElements.forEach(({ parent, original, replacement }) => {
                  parent.replaceChild(original, replacement);
                });
              });
          }).catch((error) => {
            reject(error);
            this.isPdfExport = false;
            originalElements.forEach(({ parent, original, replacement }) => {
              parent.replaceChild(original, replacement);
            });
          });
        });
      });
    },
    //父页面提交按钮将调用此方法，此方法将文书数据回传到父页面的请求方法中
    postForm() {
      this.savePDF()
        .then((blob) => {


          // 创建FormData并添加文件
          const formData = new FormData();
          formData.append('file', blob, '轻微违法违规行为免罚告知承诺书.pdf');

          window.parent.postTemplateDate(this.form, formData);
        })
        .catch(error => {
          console.error('整个保存PDF出错:', error);
        });
    },

    //选择日期时间
    receiveFromChild(data, type) {
      const TypeMap = {
        'YYYYMMDD1': 'date1',
        'YYYYMMDD2': 'date2',
        'YYYYMMDD3': 'date3',
        'YYYYMMDD4': 'date4',
        'YYYYMMDD5': 'date5',
      };
      if (TypeMap[type]) {
        this.form[TypeMap[type]] = data;
      }
    },
    // 选择单位
    selectUnitUpdateData(data) {
      data.forEach(item => {
        this.form[item.name] = item.value;
      })
    },
  }
}
</script>

<style scoped>
:deep(.el-button-print .el-button) {
  display: inline-flex !important;
  visibility: visible !important;
  opacity: 1 !important;
  width: auto;
  min-width: 100px;
  height: auto;
  padding: 8px 15px;
  background: #fff !important;
  color: #000 !important;
  border: none;
}

:deep(.el-textarea__inner) {
  box-shadow: 0 0 0 0;
  color: black;
  padding: 0;
  font-family: "仿宋", serif;
  font-size: 5mm;
  overflow-y: hidden;
  line-height: 1.3;
}

:deep(.el-textarea-hidden .el-textarea__inner) {
  box-shadow: 0 0 0 0;
  color: black;
  padding: 0;
  font-family: "仿宋", serif;
  font-size: 5mm;
  overflow-y: hidden !important;
  resize: none !important;
  height: auto !important;
}

.input-container {
  width: 100%;
  display: flex;
  flex-wrap: wrap;
  align-items: flex-start;
}

.inputStyleNoLine {
  border: none;
  outline: none;
  padding: 0px;
}

.typeSpan {
  cursor: pointer;
  font-size: 5mm;
}
</style>
